#include "MouseUtils.h"

MouseUtils::MouseUtils(ChunkManager *c, CameraManager* cam) : chunky(c), Camera(cam)
{
}

vector3<float> MouseUtils::get3DFrom2D(float x, float y){
    GLint viewport[4];
    GLdouble modelview[16];
    GLdouble projection[16];
    GLfloat winX, winY, winZ;
    GLdouble posX, posY, posZ;

    glPushMatrix();

    glRotatef(Camera->getRotY(),1,0,0);
    glRotatef(Camera->getRotX(),0,1,0);
    glTranslatef(-Camera->getEyeX(),-Camera->getEyeY(),-Camera->getEyeZ());

    glGetDoublev( GL_MODELVIEW_MATRIX, modelview );
    glGetDoublev( GL_PROJECTION_MATRIX, projection );
    glGetIntegerv( GL_VIEWPORT, viewport );

    winX = x;
    winY = viewport[3] - y;
    glReadPixels( x, winY, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &winZ );

    gluUnProject( winX, winY, winZ, modelview, projection, viewport, &posX, &posY, &posZ);

    glPopMatrix();

    return vector3<float>(posX, posY, posZ);
}
//need to fix plane. d not enough
vector3<int> MouseUtils::March(vector3<float> eye, vector3<float> lookat, float d){
    vector3<float> step=lookat.unit();
    vector3<float> testpt;
    vector3<float> plane = Camera->getLookAtVector();

    int x,y,z;
    for(float i=0;i<MARCH_LIMIT;i+=0.1){
        testpt=(step*i)+eye;
        x=FLOOR(testpt.x);
        y=FLOOR(testpt.y);
        z=FLOOR(testpt.z);

        if(chunky->isValid(x,y,z)){

            //vector3<float> v(x,y,z);
            if(d>0.0){
                if(fabs(fabs(plane.dot(testpt)-plane.dot(eye))-d)<PLANE_DRAW_EPSILON)
               return vector3<int>(x,y,z);
            }
            else if(chunky->getVoxel(x,y,z).draw())
               return vector3<int>(x,y,z);

        }else{
            //return last valid voxel
            testpt=(step*(i-0.1))+eye;
            x=FLOOR(testpt.x);
            y=FLOOR(testpt.y);
            z=FLOOR(testpt.z);
            return vector3<int>(x,y,z);
        }

    }
    //return valid voxel at step 32
     return vector3<int>(x,y,z);

}



